package cn.com.header.web.controller.sys;

import cn.com.header.core.util.ApplicationUtils;
import cn.com.header.core.util.SysProperties;
import cn.com.header.web.model.basic.*;
import cn.com.header.web.model.sys.Role;
import cn.com.header.web.model.sys.User;
import cn.com.header.web.service.basic.*;
import cn.com.header.web.service.sys.RoleService;
import cn.com.header.web.service.sys.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by yds on 2017/07/18
 */
@Controller
@RequestMapping(value = "sys/personal")
public class PersonalController {

    @Resource
    private RoleService roleService;
    @Resource
    private UserService userService;

    @Autowired
    private SubjectService subjectService;

    /**
     * 个人中心列表
     * @param req
     * @return
     */
    @RequestMapping(value="/list")
    public String personal(HttpServletRequest req) throws Exception {


        User userInfo = (User)req.getSession().getAttribute("userInfo");
        Role role = roleService.selectByUid(userInfo.getId());
        User user = userService.get(userInfo.getId());
        req.getSession().setAttribute("user",user);
        req.getSession().setAttribute("role",role);


        return "sys/personal/list";
    }


    @RequestMapping("/edit")
    public String edit(Long id,HttpServletRequest request) throws Exception {
        if(id!=null){
            User u=userService.get(id);
            request.setAttribute("vo",u);
        }
        return "sys/personal/edit";
    }
    @RequestMapping(value = "/save")
    public String save(HttpServletRequest request,Long id,String trueName,String password) throws Exception {
        User u=userService.get(id);
        u.setTrueName(trueName);
        u.setGxsj(new Date());
        u.setUserPwd(ApplicationUtils.sha256Hex(password));
        userService.saveUser(u);
        request.getSession().setAttribute("userInfo", u);
        return "redirect:list.do";
    }

    @RequestMapping(value = "/check")
    @ResponseBody
    public String check(Long id, String oldPassWord, HttpServletRequest request) throws Exception{
        JSONObject obj = new JSONObject();
        User user = userService.get(id);
        if (!ApplicationUtils.sha256Hex(oldPassWord).equals(user.getUserPwd())){
            obj.accumulate("valid",false);
            return obj.toString();
        }else {
            obj.accumulate("valid",true);
            return obj.toString();
        }

    }
}
